<template>
	<view class="content tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center">
		<view class="tn-flex tn-flex-direction-column tn-flex-row-center tn-text-center">
			<button type="balanced" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
				style="width: 320rpx; height: 320rpx;">
				<image :src="avatarUrl || '/static/missing-face.png'" style="width: 280rpx; height: 280rpx;"></image>
			</button>
			<view style="color: darkgray;">选择头像</view>
		</view>
		<view class="tn-flex tn-flex-direction-row tn-margin-top tn-flex-row-center tn-margin-bottom">
			<text class="tn-text-xxl">昵称：</text>
			<input type="nickname" class="tn-text-xl nick-name-input" :value="nickName" @blur="bindblur"
				placeholder="请输入昵称(不指定时随机生成)" @input="bindinput" />
		</view>

		<view class="tn-flex tn-margin-top tn-flex-direction-column">
			<view class="login-btn" @tap="loginAndUpdateUserInfo()">一键登录</view>
			<view class="skip-btn tn-margin-top" @tap="skipLogin()">跳过</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				avatarUrl: '',
				nickName: '',
				wxCode: '',
				localUserInfo: null,
			}
		},
		show() {
			this.login();
		},
		onLoad() {
			this.login();
		},
		methods: {
			onChooseAvatar(e) {
				console.log('微信头像信息', e)
				// 将数据赋值
				const {
					avatarUrl
				} = e.detail
				this.avatarUrl = avatarUrl
			},
			bindblur(e) {
				this.nickName = e.detail.value; // 获取微信昵称
			},
			bindinput(e) {
				this.nickName = e.detail.value; //这里要注意如果只用blur方法的话用户在输入玩昵称后直接点击保存按钮，会出现修改不成功的情况。
			},
			//登录
			login() {
				console.log('开始执行登录--->')
				let _self = this;
				// #ifdef MP-WEIXIN
				// 1. wx 获取登录用户 code
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						_self.wxCode = loginRes.code;
						_self.executeLogin(loginRes.code);
					},
					fail: () => {
						return false;
					}
				});
				// #endif
				return false;
			},
			executeLogin(code) {
				let _this = this;
				// 每次登录，都删除前一次的token
				this.$Net.removeToken();
				this.$Net.req({
					url: this.$API.execUserLogin(),
					method: "get",
					data: {
						'code': code,
					},
					dataType: 'json',
					success: function(result, status) {
						// 缓存token
						console.log('根据code执行登录 ->', result);
						_this.$Net.saveToken(result.token);
						_this.localUserInfo = result.user;
						_this.avatarUrl = _this.localUserInfo.avatar;
						_this.nickName = _this.localUserInfo.nickName;
						console.log('根据code登录成功: ', _this.localUserInfo)
					},
				});
			},
			loginAndUpdateUserInfo() {
				// #ifdef MP-WEIXIN
				if (!this.wxCode) {
					this.login();
				}
				
				if (!this.avatarUrl) {
					this.$api.msg('请选择头像');
					return false;
				}

				let nickName = this.nickName ? this.nickName.trim() : null;
				if (!nickName) {
					this.$api.msg("请输入昵称, 小于16字")
					return false;
				}
				
				if (this.avatarUrl.startsWith("wxfile:") || this.avatarUrl.startsWith("http://tmp")) {
					// 图片base64加密上传
					this.$API.imgUrlToBase64(this.avatarUrl).then(img => {
						this.updateUserInfo(img, nickName);
					})
				} else {
					this.updateUserInfo(this.avatarUrl, nickName);
				}
				// #endif
				// #ifdef H5
				let _this = this;
				this.$Net.req({
					url: this.$API.execH5login(),
					method: "get",
					data: {
						'uname': 'admin',
						'pwd': '123456'
					},
					dataType: 'json',
					success: function(result, status) {
						// 查询用户地址列表
						_this.$Net.saveToken(result.token)
						let userInfo = result.user;
						userInfo['logined'] = true;
						// 缓存用户信息
						_this.$API.putUserInfoIntoCache(userInfo);
						// 登录
						_this.$API.goBack();
						console.log('用户登录: {}', result);
					},
				})
				// #endif
			},
			updateUserInfo(avatar, nickName) {
				// 用户信息更新
				let _this = this;
				this.$Net.req({
					url: this.$API.execUpdateUserInfo(),
					method: "post",
					data: {
						'avatar': avatar,
						'nick': nickName
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					dataType: 'json',
					success: function(result, status) {
						// 缓存token
						console.log('用户登录信息: ', result);
						if (status.code == 0) {
							result.logined = true;
							_this.localUserInfo = result;
							// 缓存用户信息
							_this.$API.putUserInfoIntoCache(result);
							// 登录
							_this.$API.goBack();
						}
					},
				});
			},
			
			skipLogin() {
				// 不登陆
				// this.$Net.removeToken();
				this.$API.goBack()
			},

		}
	}
</script>

<style lang='scss'>
	page {
		background: $page-color-base;
	}

	.content {
		height: 90vh;
	}

	.nick-name-input {
		border-bottom: 1px solid #dbdbdb;
		border-top: 0px;
		border-left: 0px;
		border-right: 0px;
	}

	.login-btn {
		left: 30upx;
		right: 30upx;
		bottom: 16upx;
		z-index: 95;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 600upx;
		height: 80upx;
		font-size: 32upx;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}

	.skip-btn {
		left: 30upx;
		right: 30upx;
		bottom: 16upx;
		z-index: 95;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 600upx;
		height: 80upx;
		font-size: 32upx;
		color: #1a1a1a;
		background-color: #dbdbdb;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px #dbdbdb;
	}
</style>